package com.xys.auth.advice;

import com.xys.auth.bean.Syslog;
import com.xys.auth.controller.SyslogController;
import com.xys.auth.service.ISyslogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component("logAdvice")
@Aspect
public class SyslogAdvice {

    @Pointcut("execution(* com.xys.auth.controller.*.*(..))")
    private void syslogServicePointCut(){}

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISyslogService syslogService;

    private Date startTime;
    private Class executionClass;
    private Method executionMethod;

    @Before("syslogServicePointCut()")
    public  void doBefore(JoinPoint jp) throws NoSuchMethodException,SecurityException
    {

        startTime = new Date(); // 访问时间
// 获取访问的类
        executionClass = jp.getTarget().getClass();
// 获取访问的方法
        String methodName = jp.getSignature().getName();// 获取访问的方法的名称

        Object[] args = jp.getArgs();// 获取访问的方法的参数
        if (args == null || args.length == 0) {// 无参数
            executionMethod = executionClass.getMethod(methodName); // 只能获取无参数方法
        } else {
// 有参数，就将args中所有元素遍历，获取对应的Class,装入到一个Class[]
            Class[] classArgs = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                classArgs[i] = args[i].getClass();
            }
            executionMethod = executionClass.getMethod(methodName, classArgs);// 获取有参数方法
        }
    }


    @After("syslogServicePointCut()")
    public void doAfter(JoinPoint jp) throws Exception {

// 获取类上的@RequestMapping对象
        if (executionClass != SyslogController.class) {
            RequestMapping classAnnotation = (RequestMapping) executionClass.getAnnotation(RequestMapping.class);
            if (classAnnotation != null) {
// 获取方法上的@RequestMapping对象
                RequestMapping methodAnnotation = executionMethod.getAnnotation(RequestMapping.class);

                if (methodAnnotation != null) {

                    String url = ""; // 它的值应该是类上的@RequestMapping的value+方法上的@RequestMapping的value
                    url = classAnnotation.value()[0] + methodAnnotation.value()[0];
                    Syslog syslog = new Syslog();
// 获取访问时长
                    Long executionTime = new Date().getTime() - startTime.getTime();
// 将sysLog对象属性封装
                    syslog.setExecutionTime(executionTime);
                    syslog.setUrl(url);
// 获取ip
                    String ip = request.getRemoteAddr();
                    syslog.setIp(ip);

// 可以通过securityContext获取，也可以从request.getSession中获取
                    SecurityContext context = SecurityContextHolder.getContext(); // request.getSession().getAttribute("SPRING_SECURITY_CONTEXT")
                    String username = ((User) (context.getAuthentication().getPrincipal())).getUsername();
                    syslog.setUsername(username);

                    syslog.setMethod("[类名]" + executionClass.getName() + "[方法名]" + executionMethod.getName());

                    syslog.setVisitTime(startTime);

// 调用Service，调用dao将sysLog insert数据库
                    syslogService.save(syslog);
                }


            }
        }
    }
}
